/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.common.query.expression;

import java.util.Collection;

import com.eelpo.common.util.BlankUtils;

/**
 * <pre>
 * 
 * And和Or的表达式
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class LogicalExpression implements ParameterCriterion {

	private String link;
	private ParameterCriterion before;
	private ParameterCriterion after;

	private LogicalExpression(String link, ParameterCriterion before, ParameterCriterion after) {
		this.link = link;
		this.before = before;
		this.after = after;
	}

	public static LogicalExpression getOrExpression(ParameterCriterion before, ParameterCriterion after) {
		if (BlankUtils.isBlank(before) || BlankUtils.isBlank(after)) {
			return null;
		}
		return new LogicalExpression(OR, before, after);
	}

	public static LogicalExpression getAndExpression(ParameterCriterion before, ParameterCriterion after) {
		if (BlankUtils.isBlank(before) || BlankUtils.isBlank(after)) {
			return null;
		}
		return new LogicalExpression(AND, before, after);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.common.query.expression.ParameterCriterion#getJpql(java.lang.
	 *      StringBuilder)
	 */
	@Override
	public StringBuilder getJpql(StringBuilder jpql, String alias) {
		jpql.append(AND);
		jpql.append("(");
		int index = jpql.length();
		before.getJpql(jpql, alias);
		jpql.delete(index, index + 5);
		jpql.append(link);
		index = jpql.length();
		after.getJpql(jpql, alias);
		jpql.delete(index, index + 5);
		jpql.append(")");
		return jpql;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.common.query.expression.ParameterCriterion#getParameters(java
	 *      .util. List)
	 */
	@Override
	public Collection<Object> getParameters(Collection<Object> parameters) {
		before.getParameters(parameters);
		after.getParameters(parameters);
		return parameters;
	}
}
